import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:photo_view/photo_view.dart';


import '../../AppConfig/Config.dart';
import 'package:image/image.dart' as img;

import '../../AppConfig/LocalStorage.dart';
import '../../AppConfig/ShowDialog.dart';
import '../../http/NoLoadingGetApi.dart';
import '../../http/api.dart';
class PictureManagement extends StatefulWidget {
  const PictureManagement({super.key, required this.type, required this.dataMap});
  final int type;
  final Map dataMap;
  @override
  State<PictureManagement> createState() => _PictureManagementState();
}

class _PictureManagementState extends State<PictureManagement> {
  List imagePaths = [];
  List base64List=[];
  String? checkImage;
  List imagePaths2 = [];
  List base64List2=[];
  String? checkImage2;
  List imagePaths3 = [];
  List base64List3=[];
  String? checkImage3;
  int chkecType=-1;
  List loadImgList=[];
  List unLoadImgList=[];
  List returnImgList=[];
  String company="";
  String phone="";
  String order ="";
  List getFileList=[];
  List getFileList2=[];
  List getFileList3=[];

  final ImagePicker picker = new ImagePicker();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getphotos();
  }
  //获取图片
  void getphotos()async{
    NoLoadinggetApiManager.getData(
      context,
      "api/waybill/driver/waybill/image",
      {'waybillId':widget.dataMap['id']},
          (responseData)  {
        setState(() {
          if(responseData['data']!=null) {
            if (responseData['data']['expressContact'] != null)
              phone = responseData['data']['expressContact'];
            if (responseData['data']['expressCompany'] != null)
              company = responseData['data']['expressCompany'];
            if (responseData['data']['expressNum'] != null)
              order = responseData['data']['expressNum'];
            if (responseData['data']['loadImagePath'] != null) {
              imagePaths =
                  (responseData['data']['loadImagePath'] as List<dynamic>)
                      .map((dynamic str) =>
                  MyServiceUrl.imgHeader + str.toString())
                      .toList();
              getFileList = responseData['data']['loadImagePath'];
            }
            if (responseData['data']['unloadImagePath'] != null) {
              imagePaths2 =
                  (responseData['data']['unloadImagePath'] as List<dynamic>)
                      .map((dynamic str) =>
                  MyServiceUrl.imgHeader + str.toString())
                      .toList();
              getFileList2 = responseData['data']['unloadImagePath'];
            }
            if (responseData['data']['returnImagePath'] != null) {
              imagePaths3 =
                  (responseData['data']['returnImagePath'] as List<dynamic>)
                      .map((dynamic str) =>
                  MyServiceUrl.imgHeader + str.toString())
                      .toList();
              getFileList3 = responseData['data']['returnImagePath'];
            }
          }
        });

      },
    );
    // String?  token= await TokenManager.getToken();
    // dio.interceptors.add(InterceptorsWrapper(
    //     onRequest: (options, handler) {
    //       options.headers["satoken"] = token;
    //       return handler.next(options);
    //     }
    // ));
    // dio.get<String>(MyServiceUrl.header+'api/waybill/waybill/common/getWaybillImages?waybillId=${widget.dataMap['waybillId']}')
    //     .then((r) {
    //   setState(()   {
    //     print(r);
    //
    //     Map<String, dynamic> jsonMap = json.decode(r.toString());
    //
    //     // 获取code和data
    //     String code = jsonMap['code'].toString();
    //     if (code == "200") {
    //       if(jsonMap['data']['phone']!=null)
    //         phone=jsonMap['data']['phone'];
    //       if(jsonMap['data']['company']!=null)
    //         company=jsonMap['data']['company'];
    //       if(jsonMap['data']['orderNum']!=null)
    //         order=jsonMap['data']['orderNum'];
    //       if(jsonMap['data']['loadImages']!=null){
    //         imagePaths=  (jsonMap['data']['loadImages'] as List<dynamic>).map((dynamic str) => MyServiceUrl.imgHeader + str.toString()).toList();
    //         getFileList=jsonMap['data']['loadImages'];
    //       }
    //       //
    //       if(jsonMap['data']['unloadImages']!=null){
    //         imagePaths2=  (jsonMap['data']['unloadImages'] as List<dynamic>).map((dynamic str) => MyServiceUrl.imgHeader + str.toString()).toList();
    //         getFileList2=jsonMap['data']['unloadImages'];
    //       }
    //
    //       if(jsonMap['data']['receiptImages']!=null){
    //
    //         imagePaths3=  (jsonMap['data']['receiptImages'] as List<dynamic>).map((dynamic str) => MyServiceUrl.imgHeader  + str.toString()).toList();
    //         getFileList3=jsonMap['data']['receiptImages'];
    //       }
    //
    //       print(jsonMap['data']['loadImages']);
    //     } else {
    //       BrnToast.show(jsonMap['msg'], context);
    //     }
    //
    //   });
    // }).catchError((error) {
    //   print(error);
    // });
  }
//获取图片路径
  Future<void> uploadSingleFile(String fileData,int imgType) async {
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(
      MyServiceUrl.header +
          'api/system/dev/file/uploadSingleFile',
      data: {
        "type":imgType==1?"CompanyDocument":imgType==2?"WaybillLoadDocument": "WaybillUnloadDocument",
        "typeKey":widget.dataMap['waybillId'],
        "fileData":fileData,
        "fileFormat":"jpg"
      },
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          if(imgType==2){
            getFileList.add(jsonMap['msg']);
          }else  if(imgType==1){
            getFileList3.add(jsonMap['msg']);
          }else{
            getFileList2.add(jsonMap['msg']);
          }




        } else {
          BrnToast.show(jsonMap['msg'], context);
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }

  Future<void> editPhotosAction() async {

    LoadingDialog.show(context);
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(
      MyServiceUrl.header +
          'api/waybill/waybill/common/addImages',
      data: {
        "waybillId":widget.dataMap['waybillId'],
        "loadImages":getFileList,
        "unloadImages":getFileList2,
        "receiptImages":getFileList3,
        "phone":phone,
        "company":company,
        "orderNum":order
      },
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {

          LoadingDialog.hide(context);
          BrnToast.show("提交成功", context);
          Navigator.pop(context);

        } else {
          BrnToast.show(jsonMap['msg'], context);
          LoadingDialog.hide(context);
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;

    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.white,
        title: Text("图片管理",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
      ),
      body: Column(
        children: [
          Expanded(
            child:  ListView(
              children: [
                Container(
                  margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 13.h),
                  padding: EdgeInsets.only(left: 12.w,right: 12.w,top: 10.h,bottom: 10.h),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(10))),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 20.sp),),
                          Text("装货凭证",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                        ],
                      ),
                      SizedBox(height: 8.h,),
                      Container(
                        child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Wrap(
                            spacing: 8.0,
                            runSpacing: 8.0,
                            children: [
                              ...imagePaths.map((path) => buildImageWidget(path,1)).toList(),
                              buildAddImageWidget(1),
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 13.h),
                  padding: EdgeInsets.only(left: 12.w,right: 12.w,top: 10.h,bottom: 10.h),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(10))),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 20.sp),),
                          Text("卸货凭证",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                        ],
                      ),
                      SizedBox(height: 8.h,),
                      Container(
                        child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Wrap(
                            spacing: 8.0,
                            runSpacing: 8.0,
                            children: [
                              ...imagePaths2.map((path) => buildImageWidget(path,2)).toList(),
                              buildAddImageWidget(2),
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 13.h),
                  padding: EdgeInsets.only(left: 12.w,right: 12.w,top: 10.h,bottom: 10.h),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(10))),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 20.sp),),
                          Text("回单照片",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                        ],
                      ),
                      SizedBox(height: 8.h,),
                      Container(
                        child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Wrap(
                            spacing: 8.0,
                            runSpacing: 8.0,
                            children: [
                              ...imagePaths3.map((path) => buildImageWidget(path,3)).toList(),
                              buildAddImageWidget(3),
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                SizedBox(height: 8.h,),
                Center(
                  child: Text("新增或删除照片，请点击下方的提交按钮，提交后才生效",style: TextStyle(fontSize: 13.sp,color: MyColors.textColor),),
                ),
                SizedBox(height:8.h ,),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        SizedBox(width: 22.w,),
                        Text("物流信息",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                      padding: EdgeInsets.only(left: 12.w,right: 12.w,top: 12.h,bottom: 12.h),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.all(Radius.circular(10))),
                      child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  Text("物流公司",style: TextStyle(color:Colors.black,fontSize: 14.sp ),),
                                  Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                                ],
                              ),
                              Container(
                                width: 200.w,
                                height:35.h,
                                color: MyColors.backgreyColor,
                                child:  TextField(
                                  enabled: false,
                                  decoration: InputDecoration(
                                    hintText:  company!=""?company: '',
                                    hintStyle:TextStyle(fontSize: 13.sp,color:company!=""?Colors.black: MyColors.hintColor),
                                    filled: true,
                                    fillColor: Colors.white,
                                    border: InputBorder.none,
                                    alignLabelWithHint: true,
                                    // contentPadding: EdgeInsets.symmetric(vertical: 6.0.h, horizontal: 0.0.w),
                                  ),
                                  keyboardType: TextInputType.number,
                                  textAlign: TextAlign.right,
                                  style: TextStyle(color: Colors.black,fontSize: 14.sp),
                                  onChanged: (value) {
                                    setState(() {
                                      company = value;
                                    });
                                  },
                                ),
                              ),
                            ],
                          ),
                          Divider(height: 16.h,color: MyColors.backgreyColor,),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  Text("物流单号",style: TextStyle(color:Colors.black ,fontSize: 14.sp),),
                                  Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                                ],
                              ),
                              Container(
                                width: 200.w,
                                height:35.h,
                                color: MyColors.backgreyColor,
                                child:  TextField(
                                  enabled: false,
                                  decoration: InputDecoration(
                                    hintText: order!=""?order:'',
                                    hintStyle:TextStyle(fontSize: 13.sp,color:order!=""?Colors.black: MyColors.hintColor),
                                    filled: true,
                                    fillColor: Colors.white,
                                    border: InputBorder.none,
                                    alignLabelWithHint: true,
                                    // contentPadding: EdgeInsets.symmetric(vertical: 6.0.h, horizontal: 0.0.w),
                                  ),
                                  keyboardType: TextInputType.number,
                                  textAlign: TextAlign.right,
                                  style: TextStyle(color: Colors.black,fontSize: 14.sp),
                                  onChanged: (value) {
                                    setState(() {
                                      order=value;
                                    });
                                  },
                                ),
                              ),
                            ],
                          ),
                          Divider(height: 16.h,color: MyColors.backgreyColor,),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [

                              Text("联系电话",style: TextStyle(color:Colors.black,fontSize: 14.sp ),),

                              Container(
                                width: 200.w,
                                height:35.h,
                                color: MyColors.backgreyColor,
                                child:  TextField(
                                  enabled: false,
                                  decoration: InputDecoration(
                                    hintText: phone!=""?phone:'',
                                    hintStyle:TextStyle(fontSize: 13.sp,color:phone!=""?Colors.black: MyColors.hintColor),
                                    filled: true,
                                    fillColor: Colors.white,
                                    border: InputBorder.none,
                                    alignLabelWithHint: true,
                                    // contentPadding: EdgeInsets.symmetric(vertical: 6.0.h, horizontal: 0.0.w),
                                  ),
                                  keyboardType: TextInputType.number,
                                  textAlign: TextAlign.right,
                                  style: TextStyle(color: Colors.black,fontSize: 14.sp),
                                  onChanged: (value) {
                                    setState(() {
                                      phone=value;
                                    });
                                  },
                                ),
                              ),
                            ],
                          ),

                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          Container(
            height: 85.h,
            color: Colors.white,
            padding: EdgeInsets.only(left: 15.w,right: 15.w,top:10.h,bottom: 44.h ),
            child: Row(
              children: [
                BrnSmallMainButton(
                  title: '提交',
                  bgColor:MyColors.themeColor,
                  radius: 30,
                  width: screenSize.width-30.w,
                  fontSize: 16.sp,
                  onTap: () {
                    for (int i = 0; i < base64List.length; i++) {
                      String index = base64List[i];
                      uploadSingleFile(index,2);
                    }
                    for (int i = 0; i < base64List2.length; i++) {
                      String index = base64List2[i];
                      uploadSingleFile(index,3);
                    }
                    for (int i = 0; i < base64List3.length; i++) {
                      String index = base64List3[i];
                      uploadSingleFile(index,1);
                    }
                    BrnDialogManager.showConfirmDialog(context,
                        title: "提示",
                        message:"确认提交图片吗？",
                        cancel: "",
                        cancelWidget: GestureDetector(
                          child: Center(
                            child:  Text("我再想想",style: TextStyle(color: Colors.black),),
                          ),
                          onTap: (){
                            Navigator.pop(context);
                          },
                        ),
                        conformWidget:GestureDetector(
                          child: Center(
                            child:  Text("确认",style: TextStyle(color: MyColors.themeColor),),
                          ),
                          onTap: (){
                            Navigator.pop(context);

                            editPhotosAction();
                          },
                        ),
                        confirm:"", onConfirm: () {}, onCancel: () {
                        });
                    // for (int i = 0; i < base64List.length; i++) {
                    //   String index = base64List[i];
                    //   uploadSingleFile(index);
                    // }
                    // for (int i = 0; i < base64List3.length; i++) {
                    //   String index = base64List3[i];
                    //   uploadSingleFile(index,3);
                    //   if (i == base64List3.length - 1) {
                    //
                    //   }
                    // }
                  },
                ),
              ],
            ),


          ),
        ],
      ),

    );
  }
  Widget buildImageWidget(String imagePath,int type) {
    return Container(
      width: 85.w,
      height: 85.h,
      child: Stack(
        children: [
          GestureDetector(
            onTap: () {
              // 处理点击查看图片的逻辑
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => ImageViewer(imagePath),
                ),
              );
            },
            child:
            imagePath.contains('https')==false?
            Container(
              width: 75.w,
              height: 75.h,
              decoration: BoxDecoration(
                image: DecorationImage(

                  image: FileImage(File(imagePath)),
                  fit: BoxFit.cover,
                ),
                borderRadius: BorderRadius.circular(8.0),
              ),
            ):Container(
              width: 75.w,
              height: 75.h,
              decoration: BoxDecoration(
                image: DecorationImage(

                  image: NetworkImage(imagePath) ,
                  fit: BoxFit.cover,
                ),
                borderRadius: BorderRadius.circular(8.0),
              ),

            ),
          ),

          Positioned(
            top: 0,
            right: 0,
            child: GestureDetector(
              child: Icon(Icons.highlight_off,size: 30,color: MyColors.authTipColor,),
              onTap: () {
                setState(() {
                  print(getFileList3);
                  print(imagePath);
                  if(type==1) {
                    imagePaths.remove(imagePath);
                    if(getFileList.toSet().contains(imagePath.replaceFirst(MyServiceUrl.imgHeader, '')))
                      getFileList.remove(imagePath.replaceFirst(MyServiceUrl.imgHeader, ''));
                  }
                  if(type==2) {
                    imagePaths2.remove(imagePath);
                    if(getFileList2.toSet().contains(imagePath.replaceFirst(MyServiceUrl.imgHeader, '')))
                      getFileList2.remove(imagePath.replaceFirst(MyServiceUrl.imgHeader, ''));
                  }
                  if(type==3) {
                    imagePaths3.remove(imagePath);
                    if(getFileList3.toSet().contains(imagePath.replaceFirst(MyServiceUrl.imgHeader, '')))
                      getFileList3.remove( imagePath.replaceFirst(MyServiceUrl.imgHeader, ''));
                  }
                });
              },
            ),
          ),
        ],
        alignment: Alignment.center,
      ),
    );
  }

  Widget buildAddImageWidget(int checkType) {
    return GestureDetector(
      onTap: () async {
        setState(() {
          chkecType=checkType;
        });
        showModalBottomSheet(context: context, builder: (BuildContext context) {
          return Container(
            color: Colors.white,
            child:
            Stack(

              children: [

                Column(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment:MainAxisAlignment.center,

                  children:[

                    SizedBox(height: 8.h,),
                    Row(
                      mainAxisAlignment:MainAxisAlignment.spaceBetween,
                      children: [
                        SizedBox(width: 30.w,),
                        Text("上传照片",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 18.sp),),
                        IconButton(onPressed: (){
                          Navigator.of(context).pop();
                        }, icon:Icon(Icons.close)),
                      ],
                    ),


                    SizedBox(height: 8.h,),
                    Row(
                      children: [
                        SizedBox(width: 38.w,),
                        GestureDetector(
                          child:   Column(
                            children: [
                              Image.asset("lib/Images/Authentication/相册icon.png",width:35.w ,height: 35.h,),
                              Text("相册",style: TextStyle(color: Colors.black),),

                            ],

                          ),
                          onTap: ()async{
                            var status = await Permission.photos.request();
                            if(status==PermissionStatus.denied){
                              showPhotosFirstDialog(context);
                            }else if(status==PermissionStatus.permanentlyDenied){
                              showPhotosDialog(context);
                            }else {
                              Navigator.of(context).pop();
                              final pickedFile = await picker.pickImage(
                                  source: ImageSource.gallery);

                              if (pickedFile != null) {
                                setState(() {
                                  checkImage = pickedFile.path;
                                  printImageMemorySize(File(checkImage!));
                                  print(checkImage);
                                  compressImage(File(checkImage!));
                                });
                              }
                            }
                          },
                        ),

                        SizedBox(width: 38.w,),
                        GestureDetector(
                          child: Column(
                            children: [
                              Image.asset("lib/Images/Authentication/拍照icon.png",width:35.w ,height: 35.h,),
                              Text("拍照",style: TextStyle(color: Colors.black),),

                            ],

                          ),
                          onTap: ()async{
                            var status = await Permission.camera.request();
                            if(status==PermissionStatus.denied){
                              showCameraFirstDialog(context);
                            }else if(status==PermissionStatus.permanentlyDenied){
                              showCameraDialog(context);
                            }else {
                              Navigator.of(context).pop();
                              final pickedFile = await picker.pickImage(
                                  source: ImageSource.camera);

                              if (pickedFile != null) {
                                setState(() {
                                  checkImage = pickedFile.path;
                                  printImageMemorySize(File(checkImage!));
                                  print(checkImage);
                                  compressImage(File(checkImage!));
                                });
                              }
                            }
                          },
                        ),

                      ],
                    ),
                    SizedBox(height: 40.h,),
                  ],

                ),

              ],

            ),
          );


        });


      },
      child: Container(),
      // Image.asset("lib/Images/OrderList/图片管理上传照片.png",width: 85.w,height: 85.h,)
    );
  }

  void printImageMemorySize(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();
    print('Original Image Memory Size: ${imageBytes.length} bytes');
  }

  Future<void> compressImage(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    img.Image image = img.decodeImage(Uint8List.fromList(imageBytes))!;

    // Adjust the quality and size as needed
    img.Image compressedImage = img.copyResize(image, width: 1024);

    List<int> compressedBytes = img.encodeJpg(compressedImage, quality: 80);

    // Create a new File for the compressed image
    File compressedFile = File('${imageFile.path}_compressed.jpg');
    await compressedFile.writeAsBytes(compressedBytes);

    print('Compressed Image Size: ${compressedBytes.length} bytes');

    convertToBase64(compressedFile);
  }

  Future<void> convertToBase64(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    String base64String = base64Encode(imageBytes);

    setState(() {

      if(chkecType==1){
        imagePaths.add(checkImage.toString());
        base64List.add(base64String);

      }

      if(chkecType==2){
        imagePaths2.add(checkImage.toString());
        base64List2.add(base64String);
      }

      if(chkecType==3){
        imagePaths3.add(checkImage.toString());
        base64List3.add(base64String);
      }

    });
  }


}
class ImageViewer extends StatelessWidget {
  final String imagePath;

  ImageViewer(this.imagePath);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          // 当点击大图时，返回上一个页面
          Navigator.pop(context);
        },
        child:
        imagePath.contains('http')?
        PhotoView(
          imageProvider:NetworkImage(imagePath),
          minScale: PhotoViewComputedScale.contained * 0.8,
          maxScale: PhotoViewComputedScale.covered * 2,
        ):
        PhotoView(
          imageProvider:FileImage(File(imagePath)),
          minScale: PhotoViewComputedScale.contained * 0.8,
          maxScale: PhotoViewComputedScale.covered * 2,
        ),
      ),
    );
  }
}